# -*- coding: utf-8 -*-
import json
import os
import re
import sys

import PyPDF2
from openpyxl import Workbook
# from tqdm import tqdm
import pandas as pd
# import requests
import argparse

"""
1、文本分割成句子(text2sentence)
2、获得句子的类型（extract_type）
3、获得实体属性映射(filter_mapping.json)
4、根据属性进行预测(extract_attributes)
"""



def extract(pdf_file_path):
    file_content = read_pdf_from_file(pdf_file_path)
    # 文本分割成句子
    sentences = text2sentence(file_content)

    result = []
    result.append(["entityTag", "property", "valueTag"])
    for sentence in tqdm(sentences):
        # 因为pdf识别出来会有额外的换行，干脆全部替换了
        sentence = sentence.replace("\n", "")
        ask_type = "根据文本内容:“" + str(sentence) + "”回答实体类型是什么"
        # 询问glm的接口，获得实体类型
        sentence_type = get_answer(ask_type)

        one_group = []
        one_group.append([sentence_type, "描述", sentence])
        # 映射表是通过手都筛选出来的
        mapping_dic = json.load(open(r"filter_mapping.json", 'r', encoding='utf-8'))
        try:
            values = mapping_dic[sentence_type]
            for value in values:
                ask_result = "根据文本内容:“" + str(sentence) + "”回答" + str(value) + "是什么"
                answer = get_answer(ask_result)
                one_group.append([sentence_type, value, answer])
            result = result + one_group + [["", "", ""]]
        except:
            pass
    wirte_excel(result, filename="result.xlsx")


def set_encoder(obj):
    if isinstance(obj, set):
        return list(obj)
    raise TypeError(f'Object of type {obj.__class__.__name__} is not JSON serializable')


'''
获得实体属性映射,也就是获得mapping.json，但是最终的filter_mapping.json是经过手动筛选的
1、读文件
2、D列是实体和E列是属性
    1、利用字典，D是key，E是value
'''


def get_mapping():
    folder_path = r"指南知识图谱三元组提取"
    allFile = get_allFile_from_folder(folder_path, file_type="xlsx")
    dic = {}
    for file_path in allFile:
        df = pd.read_excel(file_path, engine='openpyxl')
        entitys = df['entityTag']
        propertys = df['property']
        for i, entity in enumerate(entitys):
            # 找到所有的临床问题
            if entity not in dic:
                dic[entity] = {propertys[i]}
            else:
                dic[entity].update({propertys[i]})

    with open(r'mapping.json', "a+", encoding="utf-8") as f:
        f.write(json.dumps(dic, ensure_ascii=False) + "\n")


# 数据写入excel
def wirte_excel(data, filename):
    # 创建一个新的 Excel 文件
    workbook = Workbook()
    # 选择默认活动表单
    sheet = workbook.active

    # 将二维数组写入表格中
    for row in data:
        sheet.append(row)

    # 保存 Excel 文件
    workbook.save(filename=filename)


# 将文本分割成句子
def text2sentence(file_content):
    print(file_content)
    sentence_regex = re.compile(r'[？。！!]')
    sentences = sentence_regex.split(file_content)
    print(len(sentences))
    punctuation = sentence_regex.findall(file_content)
    sentences = [x + y for x, y in zip(sentences, punctuation)]
    return sentences


"""
从file_path获得pdf的内容
"""


def read_pdf_from_file(file_path):
    # 遍历文件夹及其子文件夹中的所有Excel
    with open(file_path, 'rb') as pdf_file:
        pdf_reader = PyPDF2.PdfReader(pdf_file)

        # 获取PDF文件的页数
        num_pages = len(pdf_reader.pages)

        # 创建一个空字符串，用于存储PDF文本
        pdf_text = ""

        # 循环遍历每一页，将文本添加到pdf_text中
        for page in range(num_pages):
            page_obj = pdf_reader.pages[page]
            pdf_text += page_obj.extract_text()

        return pdf_text


"""
从文件夹中获取所有指定类型的文件路径
"""


def get_allFile_from_folder(folder_path, file_type="pdf"):
    file_paths = []
    for root, dirs, files in os.walk(folder_path):
        for file_name in files:
            # 判断文件类型
            if file_name.endswith('.' + file_type):
                file_paths.append(os.path.join(root, file_name))
    return file_paths


def get_answer(ask):
    print('注释，先把下面的注释掉')

    # url = "http://10.99.16.16:8899/chatGLM"
    # payload = {"prompt": ask, "history": []}
    # headers = {"Content-Type": "application/json"}
    #
    # response = requests.post(url, data=json.dumps(payload), headers=headers)
    #
    # if response.status_code == 200:
    #     return response.json()["data"]["response"]
    # else:
    #     return ("请求失败，状态码为：", response.status_code)


if __name__ == '__main__':
    text = read_pdf_from_file(r'D:\Doc\may\指南材料\指南-中文\中医\国际中医临床实践指南 干眼（2021）.pdf')
    sentences = text2sentence(text)
    print(sentences)
    with open('./res.txt', 'w', encoding='utf-8') as f:
        for s in sentences:
            f.write(s.replace("\n", ""))
    # parser = argparse.ArgumentParser()
    # parser.add_argument('--pdf_file_path', type=str, help='PDF file path')
    # args = parser.parse_args()
    # # pdf_file_path = args.pdf_file_path
    # pdf_file_path =r"D:\Doc\zzy\sciengu_chatGLM\get_preTraining_file\指南知识图谱三元组提取\中成药治疗原发性高血压临床应用指南（2021年）\中成药治疗心力衰竭临床应用指南（2021年）.pdf"
    # extract(pdf_file_path)

